import 'package:flutter/material.dart';
import '../data/game_repository.dart';
import '../entity/game.dart';

class HomeProvider extends ChangeNotifier {
  final GameRepository _gameRepository = GameRepository();

  List<Game> _games = [];
  List<Game> get games => _games;

  bool _isLoading = true; //默认进入时开始加载
  bool get isLoading => _isLoading;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  HomeProvider() {
    //构造函数中直接开始获取数据
    fetchGames();
  }

  Future<void> fetchGames() async {
    _isLoading = true;
    _errorMessage = null;
    //立即通知一次，让UI显示加载状态
    notifyListeners();

    try {
      _games = await _gameRepository.getAllGamesWithProducts();
    } catch (e) {
      _errorMessage = "加载主页游戏失败: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}